package top.szhome.framework.starter.db.interceptor;

import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.PluginUtils;
import com.baomidou.mybatisplus.extension.plugins.inner.BaseMultiTableInnerInterceptor;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.JSQLParserException;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.parser.CCJSqlParserUtil;
import net.sf.jsqlparser.schema.Table;
import net.sf.jsqlparser.statement.Statement;
import net.sf.jsqlparser.statement.select.Select;
import net.sf.jsqlparser.statement.select.WithItem;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import top.szhome.framework.core.tools.exception.SzhomeException;

import java.sql.SQLException;
import java.util.List;

/**
 * @author 唐加利
 * @date 2023/8/3
 **/
@Slf4j
public class OrderInnerInterceptor extends BaseMultiTableInnerInterceptor {

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        PluginUtils.MPBoundSql sql = PluginUtils.mpBoundSql(boundSql);
        try {
            Statement statement = CCJSqlParserUtil.parse(sql.sql());
            if(statement instanceof Select){
                processParser(statement, 0, sql.sql(), null);
            }
        } catch (JSQLParserException e) {
            log.error("SQL语句解析异常, sql={}", sql.sql(), e);
            throw new SzhomeException("6000", "SQL语句解析异常，sql=" + sql.sql(), e);
        }
    }

    @Override
    protected void processSelect(Select select, int index, String sql, Object obj) {
        final String whereSegment = (String) obj;
        processSelectBody(select.getSelectBody(), whereSegment);
        List<WithItem> withItemsList = select.getWithItemsList();
        if (!CollectionUtils.isEmpty(withItemsList)) {
            withItemsList.forEach(withItem -> processSelectBody(withItem, whereSegment));
        }
    }

    @Override
    public Expression buildTableExpression(Table table, Expression where, String whereSegment) {
        return null;
    }

}
